package com.ykdl.member.kid.regandlogin;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import net.wxxr.http.util.Constants;
import oauth.signpost.http.HttpParameters;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;
import com.ykdl.member.kid.R;
import com.ykdl.member.base.GlobalContext;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.beans.AnonymousBean;
import com.ykdl.member.kid.beans.LaunchBean;
import com.ykdl.member.kid.beans.RegisterPhonebean;
import com.ykdl.member.kid.beans.ResetPasswordBean;
import com.ykdl.member.kid.beans.ResultBean;
import com.ykdl.member.kid.beans.Web_socket_worker;
import com.ykdl.member.kid.fragments.BaseFragment_home;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.gears.HomeActivity;
import com.ykdl.member.kid.gears.WelcomeActivity;
import com.ykdl.member.kid.prefs.MyPrefs;
import com.ykdl.member.kid.util.AccessTokenKeeper;
import com.ykdl.member.kid.util.ResoureUtil;
import com.ykdl.member.kid.util.SinaConstantS;
import com.ykdl.member.kid.util.StringUtils;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

public class LoginFragment extends BaseFragment_home implements OnClickListener {

	private ImageButton  go_re,forgetpw;
	private EditText user_number, user_pw, email_addres;
	private Button gologbt;
	private String appTentID = "100522490";
//	private Tencent mTencent;
//	private Weibo mWeibo;
	private String qq_openid = "";
	private String qq_access_token = "";
	private String qq_expires_in;
	private String sina_uid = "";
	private String sina_access_token = "";
	private String sina_expires_in;
	private Dialog dialog;
	private Dialog findEmailDialog;
	private boolean isgologin = true;
	private boolean isexite = true;
	private boolean isReg = false;
	private String fromECMobileTag = null;
	private Activity mActivity;
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		 mActivity=activity;
		super.onAttach(activity);
	}
	@Override
	public View initView(LayoutInflater inflater) {
		// TODO Auto-generated method stub
		view = inflater.inflate(R.layout.fragment_login, null);
		inint();
		return view;
	}
	@Override
	public void initData(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		
	}

/*	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.regactivity_xml);
		ResoureUtil.activityList.add(this);
		if (this.getIntent().getStringExtra(KidAction.FROM) != null) {
			isexite = false;
		} else {
			isexite = true;
		}
		inint();
	}*/


	

	public void inint() {
		isReg = false;
		go_re = (ImageButton) view.findViewById(R.id.quick_login);
		go_re.setOnClickListener(this);
		forgetpw = (ImageButton) view.findViewById(R.id.forgetpw);
		forgetpw.setOnClickListener(this);
		user_number = (EditText) view.findViewById(R.id.user_number);
		user_number.setInputType(EditorInfo.TYPE_CLASS_PHONE);
		user_pw = (EditText) view.findViewById(R.id.user_pw);
		gologbt = (Button) view.findViewById(R.id.gologbt);
		gologbt.setOnClickListener(this);

		
		user_pw.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) { 
					InputMethodManager imm =(InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);  
					imm.hideSoftInputFromWindow(user_pw.getWindowToken(), 0);  
					goNativeLogin();
		        } 
				return true;
			}
		});
		
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.quick_login: //快捷登陆
			go(YZLoginActivity.class);
			break;
		case R.id.forgetpw:
			showfinddilog();
			break;
		case R.id.gologbt:
			goNativeLogin();
			break;
		case R.id.phone_user:
			go(ForgetPwActivity.class);
			break;
		case R.id.email_user:
			showfindemail();
			break;
		case R.id.cance:
			dialog.dismiss();
			break;
		case R.id.qqlog_bt:
			goQqLogin();
			break;
		case R.id.sinalog_bt:
			goSinaLogin();
			break;
		case R.id.bt_cance:
			findEmailDialog.dismiss();
			break;
		case R.id.bt_ok:
			findEmailDialog.dismiss();
			dialog.dismiss();
			if (StringUtils.checkEmail(email_addres.getText().toString())) {
				ResetPasswordByEmail();
			} else {
				Toast.makeText(mContext, "邮箱格式不正确", 1).show();
			}
			break;
		case R.id.notice:
			go(UserAgreeComentActivity.class);
			break;
		default:
			break;
		}
	}


	public void goNativeLogin() {
		if (!checkPhone()) {
			return;
		}
		if (user_pw.getText().toString().trim().length() < 1) {
			Toast.makeText(mContext, "请输入密码", 1).show();
			return;
		}
		showProgress("正在登录请稍等...");
		String pageurl = KidConfig.GET_ACCESS_TOKEN;
		HttpParameters bodyParams = new HttpParameters();
		bodyParams.put("client_id", Constants.CLIENT_ID);
		bodyParams.put("client_secret", Constants.CLIENT_SECRET);
		bodyParams.put("identity", user_number.getText().toString());
		bodyParams.put("password", user_pw.getText().toString());
		bodyParams.put("grant_type", "password");
		HttpBaseRequest request = Wxxr.getInstance().postBaseRequest(pageurl,
				bodyParams, null);
		TaskManager.startHttpRequest(request, new goRegisterTag(),
				RegisterPhonebean.class);
	}

	public void goRegister() {
		showProgress("正在注册请稍等...");
		String pageurl = KidConfig.REGISTER_EMAIL;
		HttpParameters bodyParams = new HttpParameters();
		bodyParams.put("client_id", Constants.CLIENT_ID);
		bodyParams.put("display_name", "xxx");
		bodyParams.put("email", user_number.getText().toString());
		bodyParams.put("password", user_pw.getText().toString());
		bodyParams.put("captcha_id", "N3uNKHZzWh42ujK9uD2hS5");
		bodyParams.put("captcha_code", "7res");
		HttpBaseRequest request = Wxxr.getInstance().postBaseRequest(pageurl,
				bodyParams, null);
		TaskManager.startHttpRequest(request, new goRegisterTag(),
				RegisterPhonebean.class);
	}

	class goRegisterTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			Log.e("alan", "------------goRegisterTag:" + t.toString());
			if (t instanceof RegisterPhonebean) {
				finishProgress();
				RegisterPhonebean bean = (RegisterPhonebean) t;
				if (bean.getDesc() != null) {
					Toast.makeText(mContext, bean.getDesc(), 1).show();
				} else {
					AccessTokenKeeper.keepAccessToken(getActivity(), bean);
					getWeb_socket();
					if (isgologin) {
						Toast.makeText(mContext, "登录成功", 1).show();
						MobclickAgent.onEvent(getActivity(),
								"register_users");
						istutorial();
					} else {
						Toast.makeText(mContext, "注册成功", 1).show();
						go(PerfectUserInfoActivity.class);
						getActivity().finish();
					}

				}

				Log.e("alan",
						"------------Access_token:" + bean.getAccess_token());
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "失败", 1).show();
			return true;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub

		}

	}
	public void getWeb_socket() {
		String pageurl = KidConfig.GET_WEB_SOCKET;
		HttpParameters bodyParams = new HttpParameters();
		HttpBaseRequest request = Wxxr.getInstance().getBaseRequest(pageurl);
		TaskManager.startHttpRequest(request, new getWeb_socketTag(),
				Web_socket_worker.class);
	}

	class getWeb_socketTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			if (t instanceof Web_socket_worker) {
				Web_socket_worker bean = (Web_socket_worker)t;
				if (null==bean.getError()) {
					MyPrefs.setweb_socket(mContext, "http://"+bean.getWeb_socket_worker().getHost()+":"+bean.getWeb_socket_worker().getPort());
				}else {
					Toast.makeText(mContext, "失败,"+bean.getDesc(), 1).show();
				}
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub

		}

	}


	public void ResetPasswordByEmail() {
		String pageurl = KidConfig.RESET_PASSWORD_BYEMAIL;
		HttpParameters bodyParams = new HttpParameters();
		bodyParams.put("email", email_addres.getText().toString());
		bodyParams.put("captcha_id", "C9fDL7TqEVtQScxSDwLB57");
		bodyParams.put("captcha_code", "SGDF");
		HttpBaseRequest request = Wxxr.getInstance().postBaseRequest(pageurl,
				bodyParams, null);
		TaskManager.startHttpRequest(request, new resetPasswordTag(),
				ResetPasswordBean.class);
	}

	class resetPasswordTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			if (t instanceof ResetPasswordBean) {
				ResetPasswordBean bean = (ResetPasswordBean) t;
				if (bean.getStatus() == 0) {
					Toast.makeText(mContext, "成功", 1).show();
				} else {
					Toast.makeText(mContext, "失败" + bean.getStatus(), 1).show();
				}
			}

		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub

		}

	}

	public void goToQQandSinalogin(String openid, String access_token,
			String expires_in, boolean islogon, boolean isweibo) {
		String pageurl;
		if (islogon) {
			if (isweibo) {
				pageurl = KidConfig.REGISTER_SINA;
			} else {
				pageurl = KidConfig.REGISTER_QQ;
			}

		} else {
			pageurl = KidConfig.GET_ACCESS_TOKEN;
		}
		HttpParameters bodyParams = new HttpParameters();
		bodyParams.put("client_id", Constants.CLIENT_ID);
		bodyParams.put("client_secret", Constants.CLIENT_SECRET);
		if (isweibo) {
			bodyParams.put("grant_type", "weibo");
			bodyParams.put("weibo_uid", openid);
			bodyParams.put("weibo_access_token", access_token);
			bodyParams.put("weibo_expires_in", expires_in);
		} else {
			bodyParams.put("grant_type", "qq");
			bodyParams.put("qq_openid", openid);
			bodyParams.put("qq_access_token", access_token);
			bodyParams.put("qq_expires_in", expires_in);
		}
		if (islogon) {
			bodyParams.put("display_name", "lamayuer");
			bodyParams.put("email", "lamayuer_test@7500.com.cn");
		}

		HttpBaseRequest request = Wxxr.getInstance().postBaseRequest(pageurl,
				bodyParams, null);
		TaskManager.startHttpRequest(request, new gotoQqOrSinaloginTag(openid,
				access_token, expires_in, isweibo), RegisterPhonebean.class);
	}

	class gotoQqOrSinaloginTag implements ITag {
		private String openid, access_token, expires_in;
		boolean isweibo;

		public gotoQqOrSinaloginTag(String openid, String access_token,
				String expires_in, boolean isweibo) {
			this.openid = openid;
			this.access_token = access_token;
			this.expires_in = expires_in;
			this.isweibo = isweibo;
		}

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			if (t instanceof RegisterPhonebean) {
				RegisterPhonebean bean = (RegisterPhonebean) t;
				if (bean.getError() == null) {
					Toast.makeText(mContext, "登录成功", 1).show();
					MobclickAgent.onEvent(getActivity(), "register_users");
					AccessTokenKeeper.keepAccessToken(getActivity(), bean);
					if (isReg) {
						Log.e("alan", "-----first--ok---------");
						go(PerfectUserInfoActivity.class);
						getActivity().finish();
					} else {
						istutorial();
					}

				} else {
					if (bean.getError().equals("20004")) {
						isReg = true;
						Log.e("alan", "---is--first-----------");
						goToQQandSinalogin(openid, access_token, expires_in,
								true, isweibo);
					}
				}
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "登录失败", 1).show();
			return true;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub

		}

	}

	public void goQqLogin() {
//		String SCOPE = "get_user_info,get_simple_userinfo,get_user_profile,get_app_friends,upload_photo,"
//				+ "add_share,add_topic,list_album,upload_pic,add_album,set_user_face,get_vip_info,get_vip_rich_info,get_intimate_friends_weibo,match_nick_tips_weibo";
//		BaseUiListener listener = new BaseUiListener() {
//		};
//		mTencent.login(this, SCOPE, listener);
	}

	//private class BaseUiListener implements IUiListener {

//		@Override
//		public void onCancel() {
//			// TODO Auto-generated method stub
//
//		}
//
//		@Override
//		public void onComplete(JSONObject arg0) {
//			// TODO Auto-generated method stub
//			showProgress("正在登录请稍等...");
//			String data = arg0.toString();
//			if (data.contains("openid")) {
//				qq_openid = getString(arg0, "openid");
//			}
//			if (data.contains("access_token")) {
//				qq_access_token = getString(arg0, "access_token");
//			}
//			if (data.contains("expires_in")) {
//				qq_expires_in = getString(arg0, "expires_in");
//			}
//			Log.e("alan", "-----------qq_expires_in:" + qq_expires_in
//					+ "-qq_openid:" + qq_openid + "--qq_access_token:"
//					+ qq_access_token);
//			goToQQandSinalogin(qq_openid, qq_access_token, qq_expires_in,
//					false, false);
//		}
//
//		@Override
//		public void onError(UiError arg0) {
//			// TODO Auto-generated method stub
//
//		}

//	}

	public static String getString(JSONObject obj, String key) {
		String reuslt = "";
		try {
			reuslt = obj.getString(key);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return reuslt;
	}

	public void goSinaLogin() {
	//	mWeibo.anthorize(RegActivity.this, new AuthDialogListener());
	}

//	private class AuthDialogListener implements WeiboAuthListener {
//
//		@Override
//		public void onCancel() {
//			// TODO Auto-generated method stub
//
//		}
//
//		@Override
//		public void onComplete(Bundle arg0) {
//			// TODO Auto-generated method stub
//			if (null != arg0.toString()) {
//				sina_access_token = arg0.getString("access_token");
//				sina_uid = arg0.getString("uid");
//				sina_expires_in = arg0.getString("expires_in");
//				Log.e("alan", "-----------sina_uid:" + sina_uid
//						+ "-sina_access_token:" + sina_access_token
//						+ "--sina_expires_in:" + sina_expires_in);
//				goToQQandSinalogin(sina_uid, sina_access_token,
//						sina_expires_in, false, true);
//			}
//		}
//
//		@Override
//		public void onError(WeiboDialogError arg0) {
//			// TODO Auto-generated method stub
//
//		}
//
//		@Override
//		public void onWeiboException(WeiboException arg0) {
//			// TODO Auto-generated method stub
//
//		}
//
//	}

	public void showfinddilog() {
		dialog = new Dialog(getActivity(), R.style.bubble_dialog);
		dialog.setCanceledOnTouchOutside(true);
		Window dialogWindow = dialog.getWindow();
		WindowManager manager = getActivity().getWindowManager();
		LayoutParams params = dialogWindow.getAttributes();// 获取LayoutParams
		dialogWindow.setGravity(Gravity.BOTTOM);
		params.width = manager.getDefaultDisplay().getWidth();
		dialogWindow.setAttributes(params);
		dialog.setContentView(R.layout.tofindepw);
		dialog.show();
		dialog.findViewById(R.id.phone_user).setOnClickListener(this);
		dialog.findViewById(R.id.email_user).setOnClickListener(this);
		dialog.findViewById(R.id.cance).setOnClickListener(this);
	}

	public void showfindemail() {
		findEmailDialog = new Dialog(getActivity(), R.style.signDialog);
		findEmailDialog.setContentView(R.layout.findemail);
		findEmailDialog.findViewById(R.id.bt_cance).setOnClickListener(this);
		findEmailDialog.findViewById(R.id.bt_ok).setOnClickListener(this);
		email_addres = (EditText) findEmailDialog
				.findViewById(R.id.email_addres);
		findEmailDialog.show();
	}


	public void istutorial() {
		showProgress("正在登录请稍等...");
		String pageurl = KidConfig.APP_INIT;
		HttpBaseRequest request = Wxxr.getInstance().getBaseRequest(pageurl);
		TaskManager.startHttpRequest(request, new tutorialTag(),
				LaunchBean.class);
	}

	class tutorialTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			LaunchBean launchBean = (LaunchBean) t;
			if (launchBean.getError() == null) {
				if (launchBean.getTutorial() == 0) {
					go(StateSelectActivity.class);
					getActivity().finish();
				} else {
					
						go(HomeActivity.class);
						getActivity().finish();
					
				}
			} else {
				
					go(HomeActivity.class);
					getActivity().finish();
				
			}
			if (launchBean.getJpush_tags() != null) {
				Set<String> set = new HashSet<String>(Arrays.asList(launchBean
						.getJpush_tags()));
				JPushInterface.setAliasAndTags(
						getActivity().getApplicationContext(),
						launchBean.getAlias(), set);
			} else {
				JPushInterface.setAliasAndTags(
						getActivity().getApplicationContext(),
						launchBean.getAlias(), null);
			}
			
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub

		}

	}
	public boolean checkPhone(){
		if (user_number.getText().toString().length()==11) {
			if (user_number.getText().toString().matches("[0-9]{1,}")) {
				return true;
			}else {
				Toast.makeText(mContext, "请输入正确的手机号码", 1).show();
				return false;
			}
		}else {
			Toast.makeText(mContext, "请输入正确的手机号码", 0).show();
			return false;
		}   
    }


}
